package com.alibaba.citrus.cr.mn.order.center.autofulfillmentorder.ability;

import com.alibaba.citrus.cr.common.enums.ordercenter.*;
import com.alibaba.citrus.cr.common.exception.FunctionException;
import com.alibaba.citrus.cr.mn.order.center.common.util.AssertUtils;
import com.alibaba.citrus.cr.mn.order.center.common.util.JsonUtils;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.BaseDataServiceAdapter;
import com.alibaba.citrus.cr.mn.order.center.forecastorder.entity.ForecastOrderEntity;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crforecastsales.bo.ForecastOrderBO;
import com.epoch.app.crforecastsales.bo.ForecastOrderLineBO;
import com.epoch.app.mnordercenter.autofulfillmentorderbiz.dto.RetryAutoFulfillmentOrderRequest;
import com.epoch.app.mnordercenter.model.dto.BatchQueryEmployeeByConditionRequest;
import com.epoch.app.mnordercenter.model.dto.DictionaryResponse;
import com.epoch.app.mnordercenter.model.dto.Modifiers;
import com.epoch.app.mnordercenter.service.MnOrderCenterService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author baizhuo
 * @version 1.0
 * @date 2023/9/7 12:32
 */
@Service("autoFulfillmentOrderAbility")
public class AutoFulfillmentOrderAbility {

    @Resource
    private BaseDataServiceAdapter baseDataServiceAdapter;

    @Resource
    private MnOrderCenterService mnOrderCenterService;

    /**
     * 预报子单数量校验
     * @param forecastOrderEntities
     */
    public static void subOrderNumCheck(List<ForecastOrderEntity> forecastOrderEntities) {
        long count = forecastOrderEntities.stream().mapToInt(entity -> entity.getForecastOrderBO().getForecastOrderLineBOList().size()).sum();
        if (count > 1000) {
            throw new FunctionException("OC-04-001-01-16-034");
        }
    }

    public void paramsEnumDictCheckFromDictionaryService(List<ForecastOrderEntity> forecastOrderEntities) {
        //来源系统
        List<DictionaryResponse> fromSysResponseList = baseDataServiceAdapter.queryDictionarys(DictionaryTypeEnum.FROM_SYS.getCode());
        Map<String, DictionaryResponse> fromSysMap = fromSysResponseList.stream().collect(Collectors.toMap(DictionaryResponse::getCode, Function.identity(), (k1, k2) -> k2));
        //业态
        List<DictionaryResponse> businessTypeResponseList = baseDataServiceAdapter.queryDictionarys(DictionaryTypeEnum.BUSINESS_TYPE.getCode());
        Map<String, DictionaryResponse> businessTypeMap = businessTypeResponseList.stream().collect(Collectors.toMap(DictionaryResponse::getCode, Function.identity(), (k1, k2) -> k2));
        forecastOrderEntities.forEach(forecastOrderEntity -> {
            ForecastOrderBO forecastOrderBO = forecastOrderEntity.getForecastOrderBO();
            if (!fromSysMap.containsKey(forecastOrderBO.getFromSys())) {
                throw new FunctionException("OC-01-001-01-15-006", "来源系统编码");
            }
            if (!businessTypeMap.containsKey(forecastOrderBO.getBusinessType())) {
                throw new FunctionException("OC-01-001-01-15-006", "来源系统编码");
            } else {
                // 覆盖用户传入数据
                forecastOrderBO.setBusinessTypeName(businessTypeMap.get(forecastOrderBO.getBusinessType()).getName());
            }
            if (!"false".equals(forecastOrderBO.getSubmitFlag()) && !"true".equals(forecastOrderBO.getSubmitFlag())) {
                throw new FunctionException("OC-01-001-01-15-006", "是否提交");
            }

            ForecastOrderTypeEnum forecastOrderTypeEnum = ForecastOrderTypeEnum.of(forecastOrderBO.getOrderTypeCode());
            Optional.ofNullable(forecastOrderTypeEnum).orElseThrow(() -> new FunctionException("OC-01-001-01-15-006", "订单类型编码"));

            //活动订单校验
            boolean isReplenishment = forecastOrderBO.getOrderTypeCode().equals(ForecastOrderTypeEnum.REPLENISH_FORECAST.getCode());
            if (isReplenishment) {
                forecastOrderBO.getForecastOrderLineBOList().forEach(detail -> {
                    AssertUtils.isTrue(StringUtils.isBlank(detail.getActivityCode()), "OC-01-001-01-15-001", "补货活动编码");
                    AssertUtils.isTrue(StringUtils.isBlank(detail.getActivityNumber()), "OC-01-001-01-15-001", "补货活动项目号");
                });
            } else {
                forecastOrderBO.getForecastOrderLineBOList().forEach(detail -> {
                    AssertUtils.isTrue(StringUtils.isNotBlank(detail.getActivityCode()), "OC-01-001-01-15-008", "补货活动编码");
                    AssertUtils.isTrue(StringUtils.isNotBlank(detail.getActivityNumber()), "OC-01-001-01-15-008", "补货活动项目号");
                });
            }

            // 覆盖用户传入数据
            forecastOrderBO.setOrderTypeName(forecastOrderTypeEnum.getDesc());
            forecastOrderBO.setOrderType(forecastOrderTypeEnum.getValue());


            SalesOrderDeliveryMethodEnum salesOrderDeliveryMethodEnum = SalesOrderDeliveryMethodEnum.of(forecastOrderBO.getTransportModeCode());
            Optional.ofNullable(salesOrderDeliveryMethodEnum).orElseThrow(() -> new FunctionException("OC-01-001-01-15-006", "配送方式编码"));
            // 覆盖用户传入数据
            forecastOrderBO.setTransportModeName(salesOrderDeliveryMethodEnum.getDesc());

            if (StringUtils.isNotBlank(forecastOrderBO.getCreateReasonCode())) {
                SalesOrderReasonEnum salesOrderReasonEnum = SalesOrderReasonEnum.of(forecastOrderBO.getCreateReasonCode());
                Optional.ofNullable(salesOrderReasonEnum).orElseThrow(() -> new FunctionException("OC-01-001-01-15-006", "订单原因编码"));
                forecastOrderBO.setCreateReasonName(salesOrderReasonEnum.getDesc());
            }

            // 校验扩展字段是否为JSON格式
            AssertUtils.isTrue(!JsonUtils.isValidJson(forecastOrderBO.getBizFeatures()), "OC-00-001-01-15-001", "扩展字段");
            for (ForecastOrderLineBO p : forecastOrderBO.getForecastOrderLineBOList()) {
                StockUnitEnum salesUnit = StockUnitEnum.of(p.getSaleUnitCode());
//                StockUnitEnum stockUnit = StockUnitEnum.of(p.getInventoryUnitCode());
                Optional.ofNullable(salesUnit).orElseThrow(() -> new FunctionException("OC-01-001-01-15-006", "销售单位编码"));
//                Optional.ofNullable(stockUnit).orElseThrow(() -> new FunctionException("OC-01-001-01-15-006", "库存单位编码"));

                // 覆盖用户传入数据
                p.setSaleUnitName(salesUnit.getDesc());
//                p.setStockUnitName(stockUnit.getDesc());

                // 校验扩展字段是否为JSON格式
                AssertUtils.isTrue(!JsonUtils.isValidJson(p.getBizFeatures()), "OC-00-001-01-15-001", "扩展字段");
            }
        });
    }

    /**
     * 校验重试接口参数
     * @param orderBatchRetryRequest 请求参数
     */
    public void checkOrderBatchRetryRequestParam(RetryAutoFulfillmentOrderRequest orderBatchRetryRequest) {
        AssertUtils.isTrue(StringUtils.isBlank(orderBatchRetryRequest.getReqNo()), "OC-01-001-01-15-001", "请求编号");
        AssertUtils.lengthCheck(orderBatchRetryRequest.getReqNo(), 128, true, "OC-01-001-01-15-004", "请求编号");
        AssertUtils.isTrue(StringUtils.isBlank(orderBatchRetryRequest.getModifierCode()), "OC-01-001-01-15-001", "修改人工号");
        AssertUtils.lengthCheck(orderBatchRetryRequest.getModifierCode(), 50, true, "OC-01-001-01-15-004", "修改人工号");
        invalidModifier(orderBatchRetryRequest.getModifierCode());
        AssertUtils.isTrue(CollectionUtils.isEmpty(orderBatchRetryRequest.getOrderBizNos()), "OC-01-001-01-15-001", "销售订单单号列表");
        AssertUtils.isTrue(orderBatchRetryRequest.getOrderBizNos().size() > 100, "OC-01-001-01-15-004", "orderBizNos", orderBatchRetryRequest.getOrderBizNos().size(), "100");
        Set<String> orderBizNoSet = new HashSet<>();
        for (Object stringObj : orderBatchRetryRequest.getOrderBizNos()) {
            String orderBizNo;
            try {
                orderBizNo = (String) stringObj;
            } catch (Exception e) {
                throw new FunctionException("OC-04-004-01-16-004");
            }
            if (orderBizNoSet.contains(orderBizNo)) {
                throw new FunctionException("OC-04-004-01-16-008", orderBizNo);
            } else {
                orderBizNoSet.add(orderBizNo);
            }
            AssertUtils.isTrue(StringUtils.isBlank(orderBizNo), "OC-01-001-01-15-001", "销售订单单号");
            AssertUtils.lengthCheck(orderBizNo, 50, true, "OC-01-001-01-15-004", "销售订单单号");
        }
        List<String> bisUnitCodes = Lists.newArrayList(orderBatchRetryRequest.getBusinessUnitCode());
        Map<String, String> organizationMap = baseDataServiceAdapter.baselineGetOrganizationByCodes2(bisUnitCodes);
        AssertUtils.isTrue(!organizationMap.containsKey(orderBatchRetryRequest.getBusinessUnitCode()), "OC-04-004-01-16-006");
        //校验预报单号是否有重复
    }

    /**
     * 校验修改人
     * @param modifierCode
     * @return
     */
    private Modifiers invalidModifier(String modifierCode) {
        Map<String, Modifiers> modifierMap = new HashMap<>();
        //修改人查询
        BatchQueryEmployeeByConditionRequest modifierRequest = new BatchQueryEmployeeByConditionRequest();
        modifierRequest.setWorkIdList(Collections.singletonList(modifierCode));
        Result<List<Modifiers>> modifierResult = mnOrderCenterService.batchQueryEmployeeByCondition(modifierRequest);
        if (Objects.nonNull(modifierResult) && CollectionUtils.isNotEmpty(modifierResult.getResult())) {
            modifierMap = modifierResult.getResult().stream().collect(Collectors.toMap(Modifiers::getWorkId, Function.identity(), (v1, v2) -> v1));
        }
        //修改人校验
        if (!modifierMap.containsKey(modifierCode)) {
            throw new FunctionException("OC-04-004-01-16-005", modifierCode);
        }
        Modifiers modifier = modifierMap.get(modifierCode);
        if (Objects.nonNull(modifier.getStatus()) && modifier.getStatus() != 1) {
            throw new FunctionException("OC-04-004-01-16-007", modifierCode);
        }
        return modifier;
    }

}
